"""
    billing_crud.py
    ~~~~~~~~
    

    :author: Fufu, 2024/4/24
"""
from decimal import Decimal

from fastapi_async_sqlalchemy import db
from sqlalchemy import delete
from sqlmodel import select, and_

from app.crud.base_crud import CRUDBase
from app.models import BillingModel, BillingResultsModel, ExpenseModel


class CRUDBilling(CRUDBase[BillingModel]):
    pass


crud_billing = CRUDBilling(BillingModel)


class CRUDBillingResults(CRUDBase[BillingResultsModel]):
    async def delete_results(self, em: ExpenseModel):
        """删除(日期+公司+供应商+线路)的计费结果数据"""
        stmt = delete(BillingResultsModel).where(
            and_(
                BillingResultsModel.dateline == em.dateline,
                BillingResultsModel.company_id == em.company_id,
                BillingResultsModel.vendor_id == em.vendor_id,
                BillingResultsModel.line_id == em.line_id,
            )
        )
        await db.session.execute(stmt)

    async def save_results(self, em: ExpenseModel, billing_id: int, expense: Decimal):
        """插入指定计费方式的计费结果"""
        data = BillingResultsModel(
            dateline=em.dateline,
            company_id=em.company_id,
            vendor_id=em.vendor_id,
            line_id=em.line_id,
            billing_id=billing_id,
            expense=expense,
        )
        db.session.add(data)


crud_billing_results = CRUDBillingResults(BillingResultsModel)
